package com.yuncool.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yuncool.CommonUtils;
import com.yuncool.auth.utils.SessionUser;
import com.yuncool.domain.EmailRecord;
import com.yuncool.domain.vo.EmailRequestCodeVO;
import com.yuncool.mapper.EmailRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmailService {

	@Autowired
	EmailRecordMapper emailRecordMapper;
	@Value("${aliyuncs.accessKeyId}")
	private String accessKeyId;
	@Value("${aliyuncs.accessSecret}")
	private String accessSecret;
	@Autowired
	private StringRedisTemplate redisTemplate;


	/**
	 * 发送验证码邮件
	 *
	 * @param vo
	 */
	public void sendEmail(EmailRequestCodeVO vo) {
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessSecret);
		IAcsClient client = new DefaultAcsClient(profile);
		SingleSendMailRequest request = new SingleSendMailRequest();

		String email = getEmailTemplate();

		try {
			request.setAccountName("admin@yqfeng.xyz");
			request.setFromAlias("YunCool");
			request.setAddressType(1);
			request.setTagName("Code");
			request.setReplyToAddress(false);
			request.setToAddress(vo.getToAddress());
			request.setSubject("云社区");
			email = email.replace("{operation}", vo.getOperation());
			String code = CommonUtils.getCode(4);
			redisTemplate.opsForValue().set(vo.getToAddress(), code, 5L, TimeUnit.MINUTES);
			email = email.replace("{code}", code);
			request.setHtmlBody(email);
			SingleSendMailResponse httpResponse = client.getAcsResponse(request);
			log.info("邮件服务调用成功:" + httpResponse.getRequestId());
		} catch (ClientException e) {
			//捕获错误异常码
			log.error("邮件服务调用失败:" + e.getErrCode(), e);
		}
	}

	/**
	 * 获取邮件模板
	 *
	 * @return String 模板内容
	 */
	private String getEmailTemplate() {
		URL url = EmailService.class.getClassLoader().getResource("template/email.html");
		return FileUtil.readString(Objects.requireNonNull(url), CharsetUtil.UTF_8);
	}

	/**
	 * 保存发送记录
	 *
	 * @param vo
	 */
	@Async
	public void saveRecord(EmailRequestCodeVO vo) {
		EmailRecord record = new EmailRecord();
		record.setCreateTime(new Date());
		record.setCreateUserIp(vo.getIp());
		record.setOperationType(vo.getOperation());
		record.setTargetEmail(vo.getToAddress());
		SessionUser sessionUser = new SessionUser();
		if (sessionUser.checkUserStatus()) {
			record.setCreateUserId(sessionUser.getUserDetail().getUserId());
		} else {
			record.setCreateUserId("00000000000000000000000000000000");
		}
		emailRecordMapper.insert(record);
	}
}
